package com.fancy.application.sys.permission.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fancy.application.common.constant.Constants;
import com.fancy.application.common.utils.RedisUtil;
import com.fancy.application.framework.dic.method.Dict;
import com.fancy.application.framework.dic.model.DictionaryObj;
import com.fancy.application.framework.dic.model.DictionarySimpleFieldObj;
import com.fancy.application.sys.permission.entity.Auth;
import com.fancy.application.sys.permission.entity.BaseModuleEntity;
import com.fancy.application.sys.permission.entity.FilterInfo;
import com.fancy.application.sys.permission.entity.FilterRoleInfo;
import com.fancy.application.sys.permission.service.ISysPermissionService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
public class SysPermissionService implements ISysPermissionService {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public FilterInfo getFilterInfoByModelName(String modelName) {
        List<Auth> auths = getFilters();
        Auth authData = null;
        for (Auth auth : auths) {
            if (auth.getModelName().equals(modelName)) {
                authData = auth;
                break;
            }
        }
        FilterInfo filterInfo = new FilterInfo();
        if(authData != null){
            List<String> filters = authData.getAUthFilter();
            DictionaryObj dictionaryObj =Dict.getInstance().getDictMap().get(modelName);    //获取字典的定义
            for(String filter:filters){
                if(filter.startsWith("idFieldFilter")){
                    String paramDefine = resolveIdFieldFilter(filter);  //获取参数定义
                    String columnText = "";
                    DictionarySimpleFieldObj dictionarySimpleFieldObj = getDictionarySimpleFieldObjByField(dictionaryObj,paramDefine);
                    if(dictionarySimpleFieldObj != null){
                        columnText = dictionarySimpleFieldObj.getColumn();
                        filterInfo.setAuthColumn(columnText);   //设置权限字段
                    }
                }
                if(filter.startsWith("roleFieldFilter")){
                    String paramDefine = resolveRoleFieldFilter(filter);
                    String resName = StrUtil.subBefore(paramDefine,",",false);
                    String key = StrUtil.subAfter(paramDefine,"=",true);

                    FilterRoleInfo roleInfo = new FilterRoleInfo();
                    DictionarySimpleFieldObj dictionarySimpleFieldObj = getDictionarySimpleFieldObjByField(dictionaryObj,key);
                    roleInfo.setKey(key);
                    if(dictionarySimpleFieldObj != null){
                        roleInfo.setKey(dictionarySimpleFieldObj.getColumn());
                    }else{
                        log.warn("无法获取字段 {} 参数，sql可能会失效",key);
                    }
                    roleInfo.setResName(resName);
                    filterInfo.getAuthRole().add(roleInfo);
                }
            }
        }
        return filterInfo;
    }

    private DictionarySimpleFieldObj getDictionarySimpleFieldObjByField(DictionaryObj dictionaryObj,String param){
        DictionarySimpleFieldObj simpleFieldObj = null;
        for(DictionarySimpleFieldObj dictionarySimpleFieldObj:dictionaryObj.getSimpleFieldList()){
            //后续此处需要修改逻辑
            if(StrUtil.equals(dictionarySimpleFieldObj.getName(),param)){
                simpleFieldObj = dictionarySimpleFieldObj;
                break;
            }
        }
        return simpleFieldObj;
    }


    private String resolveRoleFieldFilter(String filter) {
        String paramDefine = StrUtil.subBetween(filter,"(",")");//参数定义
        log.debug("filter参数截取出来的数据为:{}",paramDefine);
        return paramDefine;
    }

    /**
     * 解析idField过滤器
     * @param filter 过滤器定义
     * @return
     */
    private String resolveIdFieldFilter(String filter) {
        String paramDefine = StrUtil.subBetween(filter,"(",")");//参数定义
        log.debug("filter参数截取出来的数据为:{}",paramDefine);
        return paramDefine;
    }

    private List<Auth> getFilters(){
        List<BaseModuleEntity> baseModuleEntities = (List<BaseModuleEntity>) redisUtil.get(Constants.MODULE_KEY);   //设置模块列表
        List<Auth> authList = new ArrayList<>();
        baseModuleEntities.forEach(baseModuleEntity -> {
            List<Auth> auths = baseModuleEntity.getAuths();
            if(auths.size()>0){
                authList.addAll(auths);
            }
        });
        return authList;
    }

}
